/**
 * Created by admin on 2016/1/13.
 */
  'use strict';

var topicModel = require ( './topic.model');
var userModel = require ( '../user/user.model');
var jwt = require('jwt-simple');

exports.index = function (req , res) {
      var pageIndex=req.query.currentPage-1;
      topicModel.find ({},function (err , topics) {
          if ( err ) {
            return handleError (res , err);
          }
          var topicStart=pageIndex*10;
          var topicEnd=pageIndex*10+10;
          return res.status(200).json ({code:200,itemTotal:topics.length,data:topics.slice(topicStart,topicEnd)});
      });
}

exports.topicType=function(req,res){
    var type=req.params.topicType;
    var pageIndex=req.query.currentPage-1;
    topicModel.find({topicTypeEn:type} ).skip(pageIndex*10).limit(10).exec(function(err,topics){
        if ( err ) {
          return handleError ( res , err );
        }
        return res.status ( 200 ).json ({code:200,itemTotal:topics.length,data:topics});
    })
}

exports.addTopic=function(req,res){
    var token=req.headers.authorization;
    var topic=req.body;
    topic.authorId = jwt.decode(token, 'wjhuang' ).sub;
    console.log(topic);
    topicModel.create(topic,function(err,topic){
        if(err){
            console.log(err);
        }else{
            res.send({code:200,msg:'发布成功'});
        }
    })
}

exports.showTopic=function(req,res){
  var topicId=req.params.topicId;
  topicModel.findOne({_id:topicId},function(err,topic){
      if(!err){
          userModel.findOne({_id:topic.authorId},function(err,user){
              res.send({code:200,data:topic,authorInfo:user});
          })
      }
  })
}
